import type { Action } from 'element-plus'
import {
  STORAGE_MODES,
  STORAGE_TYPES,
} from '@/enum/modules/indicator'
import { uuid } from '@/utils'

import StorageModeCell from '@/views/StatisticalIndicators/components/StorageModeCell.vue'

import type { TableColumn } from '@/types/modules/public'
import type { StatisticalIndicator } from '@/types/modules/statistical-indicator'

import {
  deleteIndicatorById as _deleteIndicatorById,
  getIndicatorDetailsById as _getIndicatorDetailsById,
  queryIndicatorsByPage as _queryIndicatorsByPage,
  saveOrUpdateOneStep as _saveOrUpdateOneStep,
  saveOrUpdateThreeStep as _saveOrUpdateThreeStep,
  saveOrUpdateTwoStep as _saveOrUpdateTwoStep,
  resolveIndicatorsByExpression as _resolveIndicatorsByExpression,
} from '@/api/modules/indicator'
import type { CONTAIN_SUB } from '@/enum/modules/public'

export const STORAGE_MODES_OPTIONS = [
  { label: '实时', value: STORAGE_MODES.NOW },
  // { label: '15分钟', value: STORAGE_MODES.FIFTEEN_MINUTES },
  { label: '小时', value: STORAGE_MODES.HOUR },
  { label: '日', value: STORAGE_MODES.DAY },
  { label: '月', value: STORAGE_MODES.MONTH },
  { label: '年', value: STORAGE_MODES.YEAR },
]

export enum INDICATOR_SOURCE {
  /** 手动录入 */
  MANUAL,
  /** 计量器具录入 */
  MEASURED,
  /** 统计指标录入 */
  STATISTICAL,
}

export interface CoreListItem {
  indicatorNumber: string
  timeType: STORAGE_MODES
  type: STORAGE_TYPES
}
export type StorageModeKeys =
  keyof StatisticalIndicator['storageMode']

/** 获取 expressionType  公式状态 0-无，1-完整，2-不完整 */
function getExpressType(d: any) {
  const ret: number[] = []
  if (Number(d.calculationFormulaState) > 0) {
    // 计算公式
    ret.push(1)
  }
  if (Number(d.statisticsFormulaState) > 0) {
    // 统计公式
    ret.push(2)
  }
  return ret
}

/** 获取 storageMode, indicatorDataStoreCoreList -> storageMode */
export function getModes(
  t: STORAGE_TYPES,
  d: CoreListItem[],
) {
  return (d || [])
    .filter((v: any) => v.type === t)
    .map((v: any) => v.timeType) as STORAGE_MODES[]
}

/** storageMode -> indicatorDataStoreCoreList */
function getCoreList(d: StatisticalIndicator) {
  const storageMode = d.storageMode
  const map = {
    collect: STORAGE_TYPES.COLLECT,
    entry: STORAGE_TYPES.ENTRY,
    calculate: STORAGE_TYPES.CALCULATE,
    statistic: STORAGE_TYPES.STATISTIC,
  }
  const ret: CoreListItem[] = []

  Object.keys(storageMode).forEach((key) => {
    (storageMode[key as StorageModeKeys] || []).forEach(
      (vv) => {
        ret.push({
          indicatorNumber: d.indicatorNumber,
          timeType: vv,
          type: map[key as StorageModeKeys],
        })
      },
    )
  })

  // fix:数据存储都选无的清空 传空数组后台接口会报错
  if (ret.length === 0) {
    [
      STORAGE_MODES.NOW,
      // STORAGE_MODES.FIFTEEN_MINUTES,
      STORAGE_MODES.HOUR,
      STORAGE_MODES.DAY,
      STORAGE_MODES.MONTH,
      STORAGE_MODES.YEAR,
    ].forEach((mode) => {
      ret.push({
        indicatorNumber: d.indicatorNumber,
        timeType: mode,
        type: STORAGE_TYPES.NONE,
      })
    })
  }
  return ret
}

/** 分页查统计指标 */
export function useStatisticalIndicators(
  needLoading: boolean = true,
) {
  const [loading, setLoading] = useState(false)
  const [lists, setLists] = useShallowState<
    StatisticalIndicator[]
  >([])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: 5,
    total: 0,
  })
  const columns: TableColumn<StatisticalIndicator>[] = [
    {
      key: uuid(),
      label: '指标名称',
      prop: 'indicatorName',
      minWidth: 160,
      fixed: true,
    },
    {
      key: uuid(),
      label: '指标编码',
      prop: 'indicatorNumber',
      minWidth: 160,
    },
    {
      key: uuid(),
      label: '指标来源',
      prop: 'indicatorNumber',
      width: 120,
      render({ row }: any) {
        // console.log('值：', row);

        const a = h(
          ElTag,
          {
            effect: 'light',
          },
          {
            default: () => '手动录入',
          },
        )
        const b = h(
          ElTag,
          {
            type: 'danger',
            effect: 'light',
          },
          {
            default: () => '计量器具录入',
          },
        )
        const c = h(
          ElTag,
          {
            type: 'warning',
            effect: 'light',
          },
          {
            default: () => '统计指标录入',
          },
        )

        return row.source === 0
          ? a
          : row.source === 1
            ? b
            : c
      },
    },
    {
      key: uuid(),
      label: '计量单位',
      prop: 'unitName',
      width: 100,
    },
    {
      key: uuid(),
      label: '数据存储',
      prop: 'storageMode',
      width: 300,
      render({ row }) {
        return h(StorageModeCell, {
          mode: row.storageMode,
        })
      },
    },
    {
      key: uuid(),
      label: '计算公式',
      prop: 'calculationalExpression',
      width: 100,
      render({ row }) {
        const t = row.calculationalExpressionStatus
        return t ? (t === 1 ? '完整' : '不完整') : '无'
      },
    },
    {
      key: uuid(),
      label: '统计公式',
      prop: 'statisticalExpression',
      width: 100,
      render({ row }) {
        const t = row.statisticalExpressionStatus
        return t ? (t === 1 ? '完整' : '不完整') : '无'
      },
    },
  ]

  async function queryIndicatorsByPage(params: {
    pageNumber: number
    pageSize: number
    containSub: CONTAIN_SUB
    pointId?: number
    keyword?: string
    source?: INDICATOR_SOURCE
  }) {
    needLoading && setLoading(true)
    try {
      const { data } = await _queryIndicatorsByPage(params)
      setLists(
        (data.records || []).map((v: any) => ({
          source: v.source,
          id: v.id,
          indicatorName: v.indicatorName,
          indicatorNumber: v.indicatorNumber,
          indicatorCode: v.indicatorCode,
          unitId: 0,
          unitName: v.unit,
          expressionType: getExpressType(v),
          calculationalExpression: '',
          calculationalExpressionStatus:
            v.calculationFormulaState,
          statisticalExpression: '',
          statisticalExpressionStatus:
            v.statisticsFormulaState,
          storageMode: {
            collect: getModes(
              STORAGE_TYPES.COLLECT,
              v.indicatorDataStoreCoreList,
            ),
            entry: getModes(
              STORAGE_TYPES.ENTRY,
              v.indicatorDataStoreCoreList,
            ),
            calculate: getModes(
              STORAGE_TYPES.CALCULATE,
              v.indicatorDataStoreCoreList,
            ),
            statistic: getModes(
              STORAGE_TYPES.STATISTIC,
              v.indicatorDataStoreCoreList,
            ),
          },
        })),
      )
      pagination.total = data.total
    }
    catch (e) {
    }
    finally {
      needLoading && setLoading(false)
    }
  }

  async function confirmDel() {
    return ElMessageBox.confirm(
      '确认要删除该统计指标吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
  }

  async function deleteStatisticalIndicator(
    id: number,
    callback?: () => void,
  ) {
    const action: Action = await confirmDel().catch(e => e)
    if (action === 'confirm') {
      try {
        await _deleteIndicatorById(id)
        ElMessage.success('删除成功')
        setLists(
          unref(lists).filter((item) => {
            return item.id !== id
          }),
        )
        callback?.()
      }
      catch (e) {}
    }
  }

  async function resolveIndicatorsByExpression(
    exp: string,
  ) {
    setLists([])
    const { data } = await _resolveIndicatorsByExpression(
      exp,
    );
    (data || []).forEach((v: any) => {
      v.unitName = v.unit
      v.storageMode = {
        collect: getModes(
          STORAGE_TYPES.COLLECT,
          v.indicatorDataStoreCoreList,
        ),
        entry: getModes(
          STORAGE_TYPES.ENTRY,
          v.indicatorDataStoreCoreList,
        ),
        calculate: getModes(
          STORAGE_TYPES.CALCULATE,
          v.indicatorDataStoreCoreList,
        ),
        statistic: getModes(
          STORAGE_TYPES.STATISTIC,
          v.indicatorDataStoreCoreList,
        ),
      }
    })
    setLists(data || [])
  }

  async function saveOrUpdateOneStep(
    data: StatisticalIndicator,
  ) {
    const params: Record<string, any> = {
      id: data.id,
      indicatorName: data.indicatorName,
      indicatorNumber: data.indicatorNumber,
      unitId: data.unitId,
      unit: data.unitName,
      pointId: data.pointId!,
      pointCode: data.pointCode!,
      indicatorCode: data.indicatorCode,
    }

    if (!params.id) {
      delete params.id
      params.source = 2
    }
    try {
      const { data } = await _saveOrUpdateOneStep(
        params as any,
      )
      return data
    }
    catch (e) {
      console.warn(e)
    }
    return {}
  }
  async function saveOrUpdateTwoStep(
    data: StatisticalIndicator,
  ) {
    try {
      await _saveOrUpdateTwoStep({
        indicatorId: data.id,
        indicatorNumber: data.indicatorNumber,
        calculationFormulaContent:
          data.calculationalExpression || '',
        statisticsFormulaContent:
          data.statisticalExpression || '',
      })
      return true
    }
    catch (e) {}
    return false
  }
  async function saveOrUpdateThreeStep(
    data: StatisticalIndicator,
  ) {
    const params = {
      indicatorId: data.id,
      indicatorDataStoreCoreList: getCoreList(data),
    }
    if (!data.id) {
      ElMessage.error('请先保存指标')
      return false
    }
    try {
      await _saveOrUpdateThreeStep(params)
      return true
    }
    catch (e) {}
    return false
  }

  async function getIndicatorDetailsById(
    id: number,
  ): Promise<StatisticalIndicator | null> {
    try {
      const { data } = await _getIndicatorDetailsById(id)
      return {
        id: data.id,
        pointId: data.pointId || 0,
        pointName: data.pointName || '',
        pointCode: data.pointCode || '',
        indicatorName: data.indicatorName,
        indicatorCode: data.indicatorCode,
        indicatorNumber: data.indicatorNumber,
        unitId: data.unitId,
        unitName: data.unit,
        unitExpression: '',
        expressionType: getExpressType(data),
        calculationalExpression:
          data.calculationFormulaContent || '',
        calculationalExpressionStatus:
          data.calculationFormulaState,
        statisticalExpression:
          data.statisticsFormulaContent || '',
        statisticalExpressionStatus:
          data.statisticsFormulaState,
        storageMode: {
          collect: getModes(
            STORAGE_TYPES.COLLECT,
            data.indicatorDataStoreCoreList || [],
          ),
          entry: getModes(
            STORAGE_TYPES.ENTRY,
            data.indicatorDataStoreCoreList || [],
          ),
          calculate: getModes(
            STORAGE_TYPES.CALCULATE,
            data.indicatorDataStoreCoreList || [],
          ),
          statistic: getModes(
            STORAGE_TYPES.STATISTIC,
            data.indicatorDataStoreCoreList || [],
          ),
        },
      }
    }
    catch (e) {}
    return null
  }

  return {
    columns,
    pagination,
    /** 统计指标数据 */
    lists,
    setLists,

    /** 分页查询统计指标 */
    queryIndicatorsByPage,
    /** 删除统计指标 */
    deleteStatisticalIndicator,
    /** 解析表达式中的指标 */
    resolveIndicatorsByExpression,
    /** 获取统计指标详情 */
    getIndicatorDetailsById,
    /** 保存或更新指标(基本信息) */
    saveOrUpdateOneStep,
    /** 保存或更新指标(公式) */
    saveOrUpdateTwoStep,
    /** 保存或更新指标(数据存储) */
    saveOrUpdateThreeStep,

    /** 加载中状态 */
    loading,
    setLoading,
  }
}
